﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Windows.Media;

namespace ProcessingLite
{
    public class DefaultProcessingLiteDrawingService : IProcessingLiteDrawingService
    {
        private IDrawer _drawer;
        private ConcurrentQueue<Action> _drawingCommandsQueue = new ConcurrentQueue<Action>();
        //HACK(DS): A service should not have state... but whatever
        private bool _isStarted = false;

        public DefaultProcessingLiteDrawingService(IDrawer drawer)
        {
            _drawer = drawer;
            _drawer.DrawingCompleted += _drawer_DrawingCompleted;
        }

        #region Methods\\IProcessingLiteDrawingService
        
        public void FillPixel(int x, int y, Color color)
        {
            FillRectangle(x, y, 1, 1, color);
        }

        public void FillRectangle(int x, int y, int height, int width, Color color)
        {
            if (!_isStarted)
            {
                _drawer.FillRectangle(x, y,height, width, color);
            }
            else
            {
                _drawingCommandsQueue.Enqueue(new Action
                (
                    () =>
                    {
                        _drawer.FillPixel(x, y, color);
                    }
                ));
            }
        }

        #endregion

        void _drawer_DrawingCompleted(object sender, EventArgs e)
        {
            Action drawingCommandToExecute = null;
            _drawingCommandsQueue.TryDequeue(out drawingCommandToExecute);

            if (drawingCommandToExecute != null)
                drawingCommandToExecute.Invoke();
        }

        public ProcessingLiteMainWindow Window
        {
            get { return _drawer as ProcessingLiteMainWindow; }
        }


        
    }
}
